package com.crb.crm.manage.web.user;

import com.crb.crm.manage.enums.Oauth2Channel;
import com.crb.crm.manage.dao.OpenOauth2InfoMapper;
import com.crb.crm.manage.dao.UserMapper;
import com.crb.crm.manage.pojo.OpenOauth2Info;
import com.crb.crm.manage.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;

/**
 * @author huangjian
 * @项目名称：wyait-manage
 * @包名：com.wyait.manage.web.user
 * @类描述：
 * @创建人：wyait
 * @创建时间：2017-12-31 14:22
 * @version：V1.0
 */
@Controller
@RequestMapping("/")
public class Oauth2LoginController {

    private static final Logger logger = LoggerFactory
            .getLogger(Oauth2LoginController.class);

    @Resource
    private UserMapper userMapper;
    @Value("${app.oauth2.login}")
    private String oauth2Login;
    @Value("${app.success.redirect}")
    private String successRedirect;
    @Resource
    private OpenOauth2InfoMapper oauth2InfoMapper;


    @RequestMapping("/login")
    public String toLogin(String openId,
                          String avatar,
                          String nickName,
                          String channelCode,
                          ModelMap modelMap) {
        logger.debug("channelCode:{},openId:{},avatar:{},nickName:{}",channelCode,openId,avatar,nickName);
        modelMap.put("needAuthLocal", Boolean.FALSE);
        if(StringUtils.isNotEmpty(openId)&&StringUtils.isNotEmpty(channelCode)){
            //授权登录
            OpenOauth2Info oauth2InfoByOpenId = oauth2InfoMapper.findByOpenId(openId,channelCode);
            if(Objects.nonNull(oauth2InfoByOpenId)
                    &&Objects.nonNull(oauth2InfoByOpenId.getUserId())){
                oauth2InfoByOpenId.setAvatar(avatar);
                oauth2InfoByOpenId.setNickName(nickName);
                oauth2InfoByOpenId.setUpdateTime(new Date());
                oauth2InfoMapper.updateByPrimaryKeySelective(oauth2InfoByOpenId);
                User existUser = userMapper.selectByPrimaryKey(oauth2InfoByOpenId.getUserId());
                // 自动登录
                AuthenticationToken token = new UsernamePasswordToken(
                        existUser.getMobile(), existUser.getPassword(),
                        false);
                Subject subject = SecurityUtils.getSubject();
                subject.login(token);
                System.out.println("第三方授权登录;自动登录:" + existUser.getUsername());
                return "redirect:home";
            }else{
                modelMap.put("needAuthLocal", Boolean.TRUE);
                Oauth2Channel oauth2Channel = Oauth2Channel.valueOf(channelCode);
                modelMap.put("oauth2ChannelName", oauth2Channel.getDesc());
                modelMap.put("openId",openId);
                modelMap.put("avatar",avatar);
                modelMap.put("nickName",nickName);
                modelMap.put("channelCode",channelCode);
                return "login";
            }
        }
        return "login";
    }

    @RequestMapping("/toOauth2Login/{channelCode}")
    public void toOauth2Login(HttpServletResponse response,@PathVariable("channelCode") String channelCode) throws IOException {
        Oauth2Channel oauth2Channel = null;
        if(StringUtils.isNotBlank(channelCode)){
             oauth2Channel = Oauth2Channel.valueOf(channelCode);
            if(Objects.isNull(oauth2Channel)){
                throw new IllegalArgumentException("授权渠道找不到");
            }
        }
        String formatSuccessRedirect = String.format(successRedirect, oauth2Channel.name());
        String encodeSrcUrl = Base64Utils.encodeToString(formatSuccessRedirect.getBytes());
        String redirectUrl=String.format(
                oauth2Login,
                oauth2Channel.name(),
                oauth2Channel.getAgentId(),
                encodeSrcUrl);
        response.sendRedirect(redirectUrl);
    }
}
